<template>
	<view class="text-bold">
		<view class="edgeInsetTop"></view>
		<view class="cu-form-group">
			<view class="title">联系人</view>
			<input type="text" placeholder="姓名" v-model="addressData.username"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">手机号</view>
			<input type="number" placeholder="手机号码" maxlength="11" v-model="addressData.mobile"></input>
		</view>
		<!-- #ifdef APP -->

		<view class="cu-form-group" @tap="btnClick">
			<view class="title">所在地区</view>
			<input type="number" placeholder="选择省市区" maxlength="11" v-model="addressData.address"></input>
		</view>
		<map id="mapSelected" @tap="getLocationInfo" style="width: 690rpx; height: 100px; margin-left: 30rpx;">
		</map>
		<!-- <view class="cu-form-group area">
			<view class="click" @tap="isGetLocation"></view>
			<view class="title">地图选择</view>
			<input type="text" :value="addressData.address" placeholder="选择详细地址" disabled />
		</view> -->
		<view class="cu-form-group align-start">
			<view class="title">详细地址</view>
			<!-- 1.1.5升级 -->
			<textarea maxlength="-1" :adjust-position="false" v-model="addressData.detailed_address"
				:placeholder="addressData.adcode==''?'还没有选择地区哦~ 选择地区后完成此项':'支持智能联想，输入小区名试试~'" />
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-WEIXIN -->
		<view class="cu-form-group" @tap="btnClick">
			<view class="title">所在地区</view>
			<input type="number" placeholder="选择省市区" maxlength="11" v-model="addressData.address"></input>
		</view>
		<map id="mapSelected" @tap="isGetLocation" style="width: 690rpx; height: 100px; margin-left: 30rpx;">
		</map>
		<!-- <view class="cu-form-group area">
			<view class="click" @tap="isGetLocation"></view>
			<view class="title">地图选择</view>
			<input type="text" :value="addressData.address" placeholder="选择详细地址" disabled />
		</view> -->
		<view class="cu-form-group align-start">
			<view class="title">详细地址</view>
			<!-- 1.1.5升级 -->
			<textarea maxlength="-1" :adjust-position="false" v-model="addressData.detailed_address"
				:placeholder="addressData.adcode==''?'还没有选择地区哦~ 选择地区后完成此项':'支持智能联想，输入小区名试试~'" />
		</view>
		<!-- #endif -->

		<!-- 1.1.5升级 -->
		<!-- #ifdef H5 -->
		<view class="cu-form-group area">
			<view class="click" @tap="btnClick"></view>
			<view class="title">所在地区</view>
			<input type="text" :value="addressData.address" placeholder="选择地区" disabled />
		</view>
		<view class="cu-form-group align-start">
			<view class="title">详细地址</view>
			<!-- 1.1.5升级 -->
			<textarea maxlength="-1" @input="getInputtips" @focus="focusInputtips" @confirm="confirmInputtips"
				@blur="blurInputtips" :placeholder-style="addressData.adcode==''?'color: #bbb':''"
				:adjust-position="false" v-model="addressData.detailed_address"
				:disabled="addressData.adcode==''?true:false"
				:placeholder="addressData.adcode==''?'还没有选择地区哦~ 选择地区后完成此项':'支持智能联想，输入小区名试试~'" />
		</view>
		<!-- #endif -->
		<view class="cu-form-group margin-top-bj" v-show="addressType">
			<view class="title">设为默认</view>
			<switch @change="switchChange" :class="addressData.is_default == 1?'checked':''"
				:checked="addressData.is_default == 1"></switch>
		</view>
		<scroll-view scroll-y="true" class="tipsScroll" v-show="!addressType">
			<view class="item" v-for="(item,index) in addressList.tips" :key="index" @tap="addressTisp(item)">
				<view>{{item.address}}</view>
				<text>{{item.name}}</text>
			</view>
		</scroll-view>
		<!-- 1.0.5升级 -->
		<!-- 1.0.6升级 -->
		<view class="padding-bj flex flex-direction margin-top" v-show="addressType">
			<button @tap="confirm" class="cu-btn wanl-bg-orange lg">完成</button>
		</view>
		<wanl-address ref='wanlAddress' @selectAddress="successSelectAddress"></wanl-address>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				addressData: {
					username: '',
					mobile: '',
					is_default: 0,
					//地区
					country: '', // 国家
					province: '', //省份
					city: '', // 城市
					citycode: '', // 城市代码
					district: '', // 县
					adcode: '', // 地区代码
					address: '', //详细地区
					//详情
					address: '', //详细地址
					address_name: '', // 地址名称
					detailed_address: '', // 完整地址名称
					location: '' //经纬度
				},
				addressList: {
					location: '',
					adcode: '',
					tips: {}
				},
				addressType: true,
				title: 'map',
				latitude: 39.909, // 默认纬度
				longitude: 116.39742, // 默认经度(北京天安门)
				covers: [{
					id: 110,
					latitude: 39.909,
					longitude: 116.39742,
					iconPath: '	https://hellouniapp.dcloud.net.cn/static/location.png',
					width: "20",
					height: "20"
				}],
				controls: [{ // 控件
					id: 99,
					position: { // 控件位置
						left: 160,
						top: 120
					},
					iconPath: 'https://hellouniapp.dcloud.net.cn/static/location.png' // 控件图标
				}],
				address_info: "",
				address_info_recomd: "",
				address: ""
			}
		},
		onLoad(option) {
			let title = '新增地址 ';
			if (option.type === 'newadd') {
				this.addressData.default = 1
			}
			if (option.type === 'edit') {
				title = '编辑地址'
				this.addressData = JSON.parse(option.data)
				// 1.1.6 升级
				// if (this.addressData.address) {
				this.addressData.address = this.addressData.province_name + this.addressData.city_name + this.addressData
					.area_name
				// this.addressData.detailed_address = this.addressData.address_name + this.addressData.address;
				// }
			}
			this.manageType = option.type;
			this.$wanlshop.title(title);
		},
		onNavigationBarButtonTap() {
			this.confirm()
		},
		methods: {
			isGetLocation(a = "scope.userFuzzyLocation") { //检查当前是否已经授权访问scope属性
				var _this = this;
				uni.getSetting({
					success(res) {
						console.log(res)
						if (!res.authSetting[a]) { //每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
							console.log(888)
							_this.getAuthorizeInfo()
						} else {
							//方式一
							console.log(999)
							_this.getLocationInfo();
							// 方式二
							// _this.getLocation();
						}
					}
				});
			},
			getAuthorizeInfo(a = "scope.userFuzzyLocation") { // uniapp弹窗弹出获取授权（地理，个人微信信息等授权信息）弹窗
				var _this = this;
				uni.authorize({
					scope: a,
					success() { //允许授权
						//方式一
						_this.getLocationInfo();
						// 方式二
						console.log(5555)
						// _this.getLocation();
					}
				})
			},
			//点击地图时
			clickMap(e) {
				console.log("点击地图时:" + e);
				this.latitude = e.detail.latitude;
				this.longitude = e.detail.longitude;
			},
			getLocationInfo() {
				let that = this
				console.log(456)
				//直接调用即可
				uni.showModal({
					title: '托普装修基材对地址权限申请说明',
					content: '用于获取位置信息，我们需要申请地址权限。',
					cancelText: "取消", // 取消按钮的文字  
					confirmText: "确认", // 确认按钮的文字  
					showCancel: true, // 是否显示取消按钮，默认为 true
					confirmColor: '#f55850',
					cancelColor: '#39B54A',
					success: (res1) => {
						if (res1.confirm) {
							console.log('comfirm') //点击确定之后执行的代码

							uni.chooseLocation({
								success: (res) => {
									console.log(888888888)
									console.log(res)
									if (res.errMsg == "chooseLocation:ok") {
										that.addressData.detailed_address = res.name + res.address;
										console.log(that.addressData.detailed_address)
										that.latitude = res.latitude;
										that.longitude = res.longitude;
									}
								},
								fail: (res1) => {
									console.log(444)
									alert(JSON.stringify(res1))
									// 获取用户当前授权设置
								// 	uni.getSetting({
								// 		success: function(res) {
								// 			var statu = res.authSetting;
								// 			console.log(statu);
								// 			if (!statu['scope.userLocation']) {
								// 				console.log(123);
								// 				uni.showModal({
								// 					title: '是否授权当前位置',
								// 					content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
								// 					success(tip) {
								// 						if (tip.confirm) {
								// 							// 打开用户授权设置
								// 							uni.openSetting({
								// 								success: function(
								// 									data
								// 								) {
								// 									if (data
								// 										.authSetting[
								// 											"scope.userLocation"
								// 										] ===
								// 										true
								// 									) {
								// 										uni.showToast({
								// 											title: '授权成功',
								// 											icon: 'success',
								// 											duration: 1000
								// 										})
								// 										//授权成功之后，再调用chooseLocation选择地方
								// 										setTimeout
								// 											(function() {
								// 													uni.chooseLocation({
								// 														success: (
								// 															data
								// 														) => {
								// 															console
								// 																.log(
								// 																	'位置名称：' +
								// 																	data
								// 																	.name
								// 																);
								// 															console
								// 																.log(
								// 																	'详细地址：' +
								// 																	data
								// 																	.address
								// 																);
								// 															console
								// 																.log(
								// 																	'纬度：' +
								// 																	data
								// 																	.latitude
								// 																);
								// 															console
								// 																.log(
								// 																	'经度：' +
								// 																	data
								// 																	.longitude
								// 																);
								// 															that.addressData
								// 																.detailed_address =
								// 																data
								// 																.name +
								// 																data
								// 																.address;
								// 															// console.log(that.addressData.detailed_address)
								// 															that.latitude =
								// 																data
								// 																.latitude;
								// 															that.longitude =
								// 																data
								// 																.longitude;
								// 														}
								// 													})
								// 												},
								// 												1000
								// 											)
								// 									}
								// 								}
								// 							})
								// 						} else {
								// 							uni.showToast({
								// 								title: '授权失败',
								// 								icon: 'none',
								// 								duration: 1000
								// 							})
								// 						}
								// 					}
								// 				})

								// 			}
								// 		}
								// 	})
								
								}
							})

						} else {
							console.log('cancel') //点击取消之后执行的代码
						}
					}
				})
			},
			//获取当前所在位置的经纬度
			getLocation() {
				console.log(6666)
				// #ifdef MP
				uni.getFuzzyLocation({
					type: 'wgs84',
					success: (res) => {
						console.log(res)
						this.latitude = res.latitude.toString()
						this.longitude = res.longitude.toString()

						// 获取地理位置详情信息
						this.getLocationDetail()
					}
				});
				// #endif

				// #ifdef APP-PLUS
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						console.log(res)
						this.latitude = res.latitude.toString()
						this.longitude = res.longitude.toString()

						// 获取地理位置详情信息
						this.getLocationDetail()
					}
				});
				// #endif
			},
			//根据经纬度获取详细的地址
			getLocationDetail() {
				console.log(7777)
				uni.request({
					header: {
						"Content-Type": "application/text"
					},
					url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + this.latitude + ',' + this
						.longitude +
						'&key=W4DBZ-C4LLD-4BK4C-P74JB-5YTCO-YLB3C',
					success: (re) => {
						//成功获取到经纬度
						console.log(re)
						if (re.statusCode == 200) {
							this.address_info_recomd = re.data.result.formatted_addresses.recommend
							this.address_info = re.data.result.address_reference.town.title + re.data.result
								.address_reference.street.title + re.data.result.address_reference.landmark_l2
								.title
							this.address = re.data.result.address
							// this.saveAddress()
						} else {
							uni.showToast({
								title: '获取地理位置失败，请重试',
								icon: "none"
							})
						}
					}
				});
			},
			// 在地图渲染更新完成时触发
			regionchange(e) {
				console.log(e)
				if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
					this.mapCtx = uni.createMapContext("mapSelected"); // 创建map的上下文对象, 从而操控map组件
					this.mapCtx.getCenterLocation({
						success: (res) => {
							console.log(res)
							this.latitude = res.latitude;
							this.longitude = res.longitude;
							this.getLocationDetail();
						}
					})
				}
			},
			getLocal(success) {
				//APP端使用
				console.log(777)

				// #ifdef APP-PLUS
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					success: function(re) {
						console.log(888)
						uni.chooseLocation({
							latitude: re.latitude,
							longitude: re.longitude,
							success: function(resp) {
								/**
								 * 逆地理编码
								 * 参考 https://lbs.amap.com/api/webservice/guide/api/georegeo
								 */
								uni.request({
									url: "https://restapi.amap.com/v3/geocode/regeo",
									method: 'get',
									data: {
										location: resp.longitude + "," + resp
											.latitude, //位置坐标:格式：location=lng<经度>,lat<纬度>
										key: '1e8aba34389a21d169d1d0495106ef09', //开发密钥（web服务Key）
										radius: 0,
										extensions: 'all', //base，返回基本地址信息；all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息
										batch: false,
										roadlevel: 1
									},
									success: function(res) {
										console.log(res, '====');
										const data = res.data.regeocode;
										const province = data.addressComponent
											.province; //省
										const city = data.addressComponent.city; //市
										const district = data.addressComponent
											.district; //区
										const township = data.addressComponent
											.township; //街道
										const address = township + data?.pois[0]
											?.name + data?.pois[0]?.address;
										const reasult = {
											province,
											city,
											district,
											address,
										}
										success(reasult);
									},
									error: function(err) {
										uni.$u.toast("服务端错误，请重试");
									}

								})
							},
							fail(err) {
								uni.$u.toast("已取消");
								console.log(err, 'err');
							},
						});
					}
				});
				// #endif


				// #ifdef MP
				uni.getFuzzyLocation({
					type: 'wgs84',
					geocode: true,
					success: function(re) {
						console.log(888)
						uni.chooseLocation({
							latitude: re.latitude,
							longitude: re.longitude,
							success: function(resp) {
								/**
								 * 逆地理编码
								 * 参考 https://lbs.amap.com/api/webservice/guide/api/georegeo
								 */
								uni.request({
									url: "https://restapi.amap.com/v3/geocode/regeo",
									method: 'get',
									data: {
										location: resp.longitude + "," + resp
											.latitude, //位置坐标:格式：location=lng<经度>,lat<纬度>
										key: '1e8aba34389a21d169d1d0495106ef09', //开发密钥（web服务Key）
										radius: 0,
										extensions: 'all', //base，返回基本地址信息；all 时会返回基本地址信息、附近 POI 内容、道路信息以及道路交叉口信息
										batch: false,
										roadlevel: 1
									},
									success: function(res) {
										console.log(res, '====');
										const data = res.data.regeocode;
										const province = data.addressComponent
											.province; //省
										const city = data.addressComponent.city; //市
										const district = data.addressComponent
											.district; //区
										const township = data.addressComponent
											.township; //街道
										const address = township + data?.pois[0]
											?.name + data?.pois[0]?.address;
										const reasult = {
											province,
											city,
											district,
											address,
										}
										success(reasult);
									},
									error: function(err) {
										uni.$u.toast("服务端错误，请重试");
									}

								})
							},
							fail(err) {
								uni.$u.toast("已取消");
								console.log(err, 'err');
							},
						});
					}
				});
				// #endif


			},
			switchChange(e) {
				if (e.detail.value) {
					this.addressData.is_default = 1;
				} else {
					this.addressData.is_default = 0;
				}
			},
			btnClick() {
				this.$refs.wanlAddress.show()
			},
			successSelectAddress(address) {
				this.addressData.country = address.country;
				this.addressData.province_name = address.province;
				this.addressData.city_name = address.city;
				this.addressData.citycode = address.citycode;
				this.addressData.area_name = address.district;
				this.addressData.address = address.formatted_address;
				this.addressData.detailed_address = address.formatted_address;
				this.addressData.location = address.location;
				this.addressData.adcode = address.adcode;
				this.addressList.location = address.location;
				this.addressList.adcode = address.adcode;
			},
			//调用高德地图搜索相关地址
			getInputtips(event) {
				let keywords = event.detail.value;
				if (keywords) {
					uni.request({
						url: 'https://restapi.amap.com/v3/assistant/inputtips',
						data: {
							key: '1e8aba34389a21d169d1d0495106ef09',
							keywords: keywords,
							location: this.addressList.location,
							city: this.addressList.adcode
						},
						success: (res) => {
							let addressList = [];
							// 1.1.7升级
							if (res.res.infocode == 10001) {
								this.$wanlshop.msg('后台未配置高德地图KEY，不支持联想，完成编辑后点击空白展开全部');
							} else {
								res.res.tips.forEach(item => {
									if (item.address.length == 0) {
										item.address = '暂未收录地址';
										item.location = '113.294701,22.666562';
									}
									addressList.push(item);
								});
							}
							this.addressList.tips = addressList;
						}
					});
				}
			},
			// 详细地址失去焦点
			blurInputtips(event) {
				this.addressData.address = event.detail.value;
				setTimeout(() => {
					this.addressType = true;
				}, 10);
			},
			// 详细地址已完成
			confirmInputtips(event) {
				this.addressType = true;
			},
			// 详细地址获取焦点
			focusInputtips(event) {
				this.addressType = false;
			},
			// 详细地址替换
			addressTisp(data) {
				this.addressData.adcode = data.adcode;
				this.addressData.address = data.address;
				this.addressData.address_name = data.name;
				// 1.0.5升级
				if (data.address) {
					this.addressData.detailed_address = this.addressData.address_name + this.addressData.address;
				}
				this.addressData.location = data.location;
				this.addressType = true;
			},
			//提交
			confirm() {
				let data = this.addressData;
				// alert(JSON.stringify(data))
				if (!data.username) {
					this.$wanlshop.msg('请填写收货人姓名');
					return;
				}
				if (!/^1[0-9]{10,10}$/.test(data.mobile)) { // 1.0.2升级
					this.$wanlshop.msg('请输入正确的手机号码');
					return;
				}
				// if (!data.city) {
				// 	this.$wanlshop.msg('请选择地区');
				// 	return;
				// }
				// if (!data.address) {
				// 	this.$wanlshop.msg('请填写详细信息');
				// 	return;
				// }
				this.$wanlshop.prePage().refreshList(data, this.manageType);
				this.$wanlshop.msg(`地址${this.manageType=='edit' ? '修改': '添加'}成功`);
				this.$wanlshop.back(1);
			}
		}
	}
</script>

<style>
	.cu-form-group {
		padding: 0 25rpx;
	}

	/* 1.1.5升级 */
	.cu-form-group.area {
		position: relative;
	}

	.cu-form-group.area .click {
		position: absolute;
		z-index: 99;
		right: 0;
		left: 0;
		top: 0;
		bottom: 0;
	}

	.cu-form-group .title {
		min-width: calc(4em + 15px);
		font-size: 28rpx;
	}

	.cu-form-group input,
	.cu-form-group textarea {
		font-size: 28rpx;
	}

	.cu-btn.lg {
		font-size: 32rpx;
		height: 86rpx;
	}

	.tipsScroll {
		width: 100%;
		height: 500rpx;
		padding: 0 50rpx;
	}

	.tipsScroll .item {
		margin: 25rpx 0;
	}

	.tipsScroll .item view {
		color: #B8B8B8;
		font-size: 22rpx;
	}

	.tipsScroll .item text {
		color: #333;
	}
</style>